package org.graduation.ical.controller;

import org.graduation.ical.service.ICSService;
import org.graduation.ical.service.UserAndICSKeyService;
import org.graduation.model.common.ResponseResult;
import org.graduation.model.common.ics.UserAndICSKey;
import org.graduation.model.common.user.User;
import org.graduation.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/ics")
public class ICSController {
    @Autowired
    private ICSService icsService;
    @Autowired
    private UserAndICSKeyService userAndICSKeyService;
    @Autowired
    private Token token;

    @GetMapping(value = "/subscribe")
    public ResponseEntity<String> subscribe(HttpServletRequest request, @RequestParam("auth") String auth) {
        String icsStr = icsService.generatorCalendar(auth).toString();
        icsStr = icsStr.replace("\r", "");
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType("text/calendar"))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=event.ics")
                .body(icsStr);
    }

    @RequestMapping(value = "/calendar", method = RequestMethod.GET)
    public ResponseResult calendar(HttpServletRequest request) {
        int uid = token.getUidByToken(token.getTokenByRequest(request));
        User u = new User();
        u.setUid(uid);
        return ResponseResult.success(icsService.getCalendarList(u));
    }

    @PostMapping("/auth/reset")
    public ResponseResult<String> reset(HttpServletRequest request) {
        int uid = token.getUidByToken(token.getTokenByRequest(request));
        return ResponseResult.success(userAndICSKeyService.resetKey(uid));
    }

    @GetMapping("/auth")
    public ResponseResult<String> auth(HttpServletRequest request) {
        int uid = token.getUidByToken(token.getTokenByRequest(request));
        UserAndICSKey userAndICSKey = userAndICSKeyService.getById(uid);
        return ResponseResult.success(userAndICSKey == null ? "" : userAndICSKey.getIcsKey());
    }
}
